'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} =  this;
        let {username,password} = ctx.request.body;
        if(username && password){
            //参数没有问题
            //1.查询用户是否存在
            let target = await service.user.selectUser(username);
            if(target.length){
                //此用户名已存在
                ctx.body = {
                    code:4,
                    msg:'此用户名已存在，请换用户名'
                }
            }else{
                //没有存在,添加
                try{
                    //加密
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        let {ctx,service} =  this;
        let {username,password} = ctx.request.body;
        if(username && password){
             //加密
             let hmcPwd = ctx.helper.hmc(password);
            let target = await service.user.login(username,hmcPwd);
            if(target.length){
                //登录成功，生成token
                let token  = jwt.sign({username},'lixd',{expiresIn:60*60*1})

                let {role_name,role_id} = target[0];
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    role_name,
                    role_id
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //获取左侧菜单
    async menu(){
        let {ctx,service} = this;
        let {role_id} = ctx.request.query;

        if(role_id){
            let list = await service.user.menu(role_id);
            ctx.body = {
                code:1,
                data:list
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
